// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 获取数据库
const db = cloud.database();
const col = db.collection('lesson');
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  // 找到对应_openid的数据
  let user = await col.where({
    '_openid': wxContext.OPENID,
  }).get();

  // 因为找到的是数组,所以需要赋值到user
  user = user.data[0];

  // 判断当前用户是否已经抽过奖，如果prize为Null为没抽过
  if(user.prize !== null){
    return {
      msg: '您已经抽过奖了！',
      success: false
    }
  }

  // 随机生成一个数
  let rand = Math.random();
  let prize;
  let integral;
  let prizeGrade;
  // 如果随机数分别在对应的区间，对应不同的奖品
  switch(true){
    case(rand < 0.1):
      prize = 'https://636c-cloud-dev-d23262-1258412313.tcb.qcloud.la/mycard_icon_onepreice.png?sign=e972b9ece04231bde0e63663704cb53c&t=1547091603';
      integral = 10000;
      prizeGrade = '一等奖';
      break;
    case (rand >= 0.1 && rand < 0.4):
      prize = 'https://636c-cloud-dev-d23262-1258412313.tcb.qcloud.la/secondPrize.png?sign=0fb91fd9e4a3c8c404acc2dfac9d829e&t=1547091639';
      integral = 5000;
      prizeGrade = '二等奖';
      break;
    case (rand >= 0.4):
      prize = 'https://636c-cloud-dev-d23262-1258412313.tcb.qcloud.la/awPrize.png?sign=04b4f77f5fde6d5f216d10358cc0f9f9&t=1547091571';
      integral = 1000;
      prizeGrade = '安慰奖';
      break;
  }

  // 拿到从合成页面传递过来的数组selectedArr，将成员作为下标
  let zero = event.selectedArr[0];
  let one = event.selectedArr[1];

  // 在对应下标的邮卡的数量number -= 1
  user.words[zero].number -= 1;
  user.words[one].number -= 1;

  // 找到并更新当前用户的prize和words
  await col.where({
    '_openid': wxContext.OPENID,
  }).update({
    data: {
      prize: prize,
      words: user.words,
      integral: integral,
      prizeGrade: prizeGrade
    }
  })

  // 返回获得的奖励
  return {
    prize: prize,
    integral: integral,
    prizeGrade: prizeGrade,
    success: true,
    words: user.words
  }
}